package com.mdd.front.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mdd.common.entity.server.Sys;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.excel.util.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.mdd.common.config.GlobalConfig;
import com.mdd.common.core.AjaxResult;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.UserBlacklist;
import com.mdd.common.entity.UserCommemorate;
import com.mdd.common.entity.UserFriend;
import com.mdd.common.entity.UserFriendGroup;
import com.mdd.common.entity.UserFriendRequest;
import com.mdd.common.entity.UserTask;
import com.mdd.common.entity.user.User;
import com.mdd.common.mapper.UserBlacklistMapper;
import com.mdd.common.mapper.UserCommemorateMapper;
import com.mdd.common.mapper.UserFriendGroupMapper;
import com.mdd.common.mapper.UserFriendMapper;
import com.mdd.common.mapper.UserFriendRequestMapper;
import com.mdd.common.mapper.UserTaskMapper;
import com.mdd.common.mapper.user.UserMapper;
import com.mdd.common.util.ConfigUtils;
import com.mdd.common.util.StringUtils;
import com.mdd.common.util.TimeUtils;
import com.mdd.common.util.UrlUtils;
import com.mdd.front.service.IFriendService;
import com.mdd.front.validate.common.PageValidate;
import com.mdd.front.vo.friend.FriendInfoVo;
import com.mdd.front.vo.friend.UserCommemorateVo;
import com.mdd.front.vo.user.UserLableGroupVo;

import cn.hutool.core.bean.BeanUtil;

@Service
public class FriendServiceImpl implements IFriendService {

	@Autowired
	private UserFriendMapper userFriendMapper;
	@Autowired
	private UserFriendRequestMapper userFriendRequestMapper;
	@Autowired
	private UserFriendGroupMapper userFriendGroupMapper;
	@Autowired
	private UserBlacklistMapper userBlacklistMapper;
	@Autowired
	private UserCommemorateMapper userCommemorateMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserTaskMapper userTaskMapper;


	@Override
	public AjaxResult<Object> importCommunicateUser(List<UserFriend> list,Integer userId) {
		/*for(UserFriend userFriend:list){
			System.out.println("userFriend.getId"+userFriend.getId());
			System.out.println("userFriend.getUserId"+userFriend.getUserId());
			System.out.println("userFriend.getName"+userFriend.getName());
			System.out.println("userFriend.getPhone"+userFriend.getPhone());
			System.out.println("userFriend.getBirthday"+userFriend.getBirthday());
		}*/
		list.stream().forEach(friend ->{
			//System.out.println("join userFriend.getId");
//			UserFriend uf = userFriendMapper.selectOne(new LambdaQueryWrapper<UserFriend>().eq(UserFriend::getPhone, friend.getPhone()));
//			if(null != uf) {
//				friend.setUid(userId);
//				friend.setUpdateTime(System.currentTimeMillis() / 1000);
//				friend.setName(friend.getName());
//				userFriendMapper.insert(friend);
//			}else {
//				friend.setUid(userId);
//				friend.setCreateTime(System.currentTimeMillis() / 1000);
//				friend.setUpdateTime(System.currentTimeMillis() / 1000);
//				userFriendMapper.insert(friend);
//			}
			Long count  = userFriendMapper.selectCount(new LambdaQueryWrapper<UserFriend>().eq(UserFriend::getPhone, friend.getPhone())
					.eq(UserFriend::getUid, userId));
			if(count == 0) {
				friend.setUid(userId);
				friend.setCreateTime(System.currentTimeMillis() / 1000);
				friend.setUpdateTime(System.currentTimeMillis() / 1000);
				userFriendMapper.insert(friend);
			}
		});
		
		
//		Map<String, String> map = list.stream().collect(Collectors.toMap(UserFriend::getPhone, UserFriend::getName));
//		List<String> phoneList = list.stream().map(UserFriend::getPhone).collect(Collectors.toList());
//		List<UserFriend> existList = userFriendMapper.selectList(new LambdaQueryWrapper<UserFriend>().in(UserFriend::getPhone, phoneList));
//		// 存在 , 进行修改
//		if(CollectionUtils.isNotEmpty(existList)) {
//			List<UserFriend> addUserList = new ArrayList<UserFriend>();
//			existList.stream().forEach(friend ->{
//				friend.setUid(userId);
//				friend.setUpdateTime(System.currentTimeMillis() / 1000);
//				for (String key : map.keySet()) {
//					if(friend.getPhone().equals(key)) {
//						friend.setName(map.get(key));
//					}
//				}
//				friend.setUpdateTime(System.currentTimeMillis() / 1000);
//				userFriendMapper.updateById(friend);
//			});
//			// 添加
//			
//			
//		}else {
//			list.stream().forEach(friend ->{
//				friend.setUid(userId);
//				friend.setCreateTime(System.currentTimeMillis() / 1000);
//				friend.setUpdateTime(System.currentTimeMillis() / 1000);
//				userFriendMapper.insert(friend);
//			});
//		}
		
		
		
		// 如果手机号码已经存在 uid 为空则修改 如果uid不为空 则不管 
		
		// 如果手机号不存在则不管
		
		
		
		return AjaxResult.success();
	}


	@Override
	public List<UserFriend> friendList(Integer userId,String keyword) {
		//		Integer pageNo = 1;
		//		Integer pageSize = 10000;
		//		MPJQueryWrapper<UserFriendRequest> mpjQueryWrapper = new MPJQueryWrapper<>();
		//		mpjQueryWrapper.select("f.id,f.user_id,f.head_pic,f.name,f.phone,DATE_FORMAT(f.birthday,'%m月%d日') as birthday,f.address,f.position,"
		//				+ "f.unit_name,f.tax_number,f.unit_address,f.unit_phone,f.bank_name,f.bank_card");
		//		mpjQueryWrapper.leftJoin("?_user_friend f on (t.user_id = f.user_id or2 t.to_user_id = f.user_id)".replace("?_", GlobalConfig.tablePrefix));
		//		mpjQueryWrapper.eq("t.to_user_id", userId).or().eq("t.user_id", userId);
		//		mpjQueryWrapper.eq("t.type", 1);
		//		mpjQueryWrapper.eq("t.status", 1);
		//		mpjQueryWrapper.orderByDesc("t.create_time");
		//		IPage<FriendInfoVo> iPage = userFriendRequestMapper.selectJoinPage( new Page<>(pageNo, pageSize), FriendInfoVo.class, mpjQueryWrapper);
		//		return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), iPage.getRecords());
		LambdaQueryWrapper<UserFriendRequest> lambdaQueryWrapper = new LambdaQueryWrapper<UserFriendRequest>();
		lambdaQueryWrapper.eq(UserFriendRequest::getType, 1);
		lambdaQueryWrapper.eq(UserFriendRequest::getStatus, 1);
		lambdaQueryWrapper.and(i ->i.eq(UserFriendRequest::getUserId, userId).or().eq(UserFriendRequest::getToUserId, userId));
		List<UserFriendRequest> list = userFriendRequestMapper.selectList(lambdaQueryWrapper);
		List<UserFriend> resultList = new ArrayList<UserFriend>();
		List<UserFriend> resultList2 = new ArrayList<UserFriend>();
		List<Integer> userIds = new ArrayList<Integer>();
		if(CollectionUtils.isNotEmpty(list)) {
			for (UserFriendRequest userFriendRequest : list) {
				if(userId.intValue() == userFriendRequest.getUserId().intValue()) {
					userIds.add(userFriendRequest.getToUserId());
				}else {
					userIds.add(userFriendRequest.getUserId());
				}
			}
			LambdaQueryWrapper<UserFriend> lambdaQueryWrapper2 = new LambdaQueryWrapper<UserFriend>();
			lambdaQueryWrapper2.in(UserFriend::getUserId, userIds);
			lambdaQueryWrapper2.eq(UserFriend::getUid, userId);
			if(StringUtils.isNotEmpty(keyword)) {
				lambdaQueryWrapper2.and(i ->i.like(UserFriend::getName, keyword).or().like(UserFriend::getPhone, keyword));
			}
			lambdaQueryWrapper2.groupBy(UserFriend::getUserId);
			resultList = userFriendMapper.selectList(lambdaQueryWrapper2);

			/*
			LambdaQueryWrapper<UserFriend> lambdaQuery2 = new LambdaQueryWrapper<UserFriend>();
			lambdaQuery2.eq(UserFriend::getUserId,userId);
			lambdaQuery2.groupBy(UserFriend::getUserId);
			resultList2 = userFriendMapper.selectList(lambdaQuery2);*/


			resultList.stream().forEach(result ->{
				if(null != result.getBirthday()) {
					result.setBirthdayShow(DateUtils.format(result.getBirthday(), "MM月dd日"));
				}
				if(StringUtils.isNotEmpty(result.getName())) {
					result.setNickName(result.getName());
				}else {
					// 查询nickname
					User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, result.getUserId()).select(User::getId,User::getNickname));
					if(null != user && StringUtils.isNotEmpty(user.getNickname())) {
						result.setNickName(user.getNickname());
					}
				}
				
			});
		}
		return resultList;
	}


	@Override
	public PageResult<UserFriend> communicateList(Integer userId, PageValidate pageValidate,String keyword) {
		Integer pageNo = pageValidate.getPageNo();
		Integer pageSize = pageValidate.getPageSize();
		Page<UserFriend> iPage = userFriendMapper.selectPage(new Page<>(pageNo, pageSize), new LambdaQueryWrapper<UserFriend>().eq(UserFriend::getUid, userId).and(wrapper -> wrapper.like(UserFriend::getPhone, keyword).or().like(UserFriend::getName, keyword)));
		iPage.getRecords().stream().forEach(user ->{
			if(null != user.getBirthday()) {
				user.setBirthdayShow(DateUtils.format(user.getBirthday(), "MM月dd日"));
				user.setBirthdayYmd(DateUtils.format(user.getBirthday(), DateUtils.DATE_FORMAT_10));
			}
			// 是否是好友
			if(null != user.getUserId()) {
				LambdaQueryWrapper<UserFriendRequest> qw = new LambdaQueryWrapper<UserFriendRequest>();
				qw.eq(UserFriendRequest::getType, 1);
				qw.and(i->i.eq(UserFriendRequest::getUserId, userId).or().eq(UserFriendRequest::getToUserId, userId));
				qw.eq(UserFriendRequest::getStatus, 1);
				qw.and(i->i.eq(UserFriendRequest::getUserId, user.getUserId()).or().eq(UserFriendRequest::getToUserId, user.getUserId()));
				Long count = userFriendRequestMapper.selectCount(qw);
				if(count > 0) {
					user.setIsFriend(1);
				}
			}
		});
		return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), iPage.getRecords());
	}


	@Override
	public AjaxResult<Object> addCommunicateUser(UserFriend userFriend, Integer userId) {
//		UserFriend uf = userFriendMapper.selectOne(new LambdaQueryWrapper<UserFriend>().eq(UserFriend::getPhone, userFriend.getPhone()
//				).eq(UserFriend::getUid, userId).last("limit 1"));
//		if(null != uf) {
//			return AjaxResult.failed("该手机号码已添加");
//		}
		userFriend.setUid(userId);
		userFriend.setCreateTime(System.currentTimeMillis() / 1000);
		userFriend.setUpdateTime(System.currentTimeMillis() / 1000);
		//User user = userMapper.selectOne(new Page<>(pageNo, pageSize), new LambdaQueryWrapper<UserFriend>().eq(UserFriend::getUid, userId))
		User user = userMapper.selectOne(new QueryWrapper<User>()
				.select("id")
				.eq("mobile", userFriend.getPhone())
				.last("limit 1"));
		//为空则代表这个用户还没注册 注册之后在添加第二条记录 不为空则添加第二条
		if(user != null){
			userFriend.setUserId(user.getId());
			//添加第二条记录
			UserFriend userFriendOther = new UserFriend();
			User userOther = userMapper.selectOne(new QueryWrapper<User>()
					.eq("id", userFriend.getUid())
					.last("limit 1"));
			BeanUtil.copyProperties(userFriend, userFriendOther);
			userFriendOther.setUid(userFriend.getUserId());
			userFriendOther.setUserId(userFriend.getUid());
			userFriendOther.setCreateTime(System.currentTimeMillis() / 1000);
			userFriendOther.setUpdateTime(System.currentTimeMillis() / 1000);
			userFriendOther.setName(userOther.getNickname());
			userFriendOther.setPhone(userOther.getMobile());
			userFriendMapper.insert(userFriendOther);
		}else {
			userFriendMapper.insert(userFriend);
		}
		return AjaxResult.success();
	}

	@Override
	public AjaxResult<Object> updCommunicateUser(UserFriend userFriend, Integer userId) {
		UserFriend oldUserFriedn = userFriendMapper.selectById(userFriend.getId());
		//如果手机号码有改动则判断手机号码是否已经存在
		if(!oldUserFriedn.getPhone().equals(userFriend.getPhone())) {
			Long count = userFriendMapper.selectCount(new LambdaQueryWrapper<UserFriend>()
					.eq(UserFriend::getPhone, userFriend.getPhone()).ne(UserFriend::getId, userFriend.getId()));
			if(count > 0) {
				return AjaxResult.failed("该手机号码已添加");
			}
		}
		return userFriendMapper.updateById(userFriend)==1?AjaxResult.success():AjaxResult.failed("修改失败");
	}


	@Override
	public PageResult<FriendInfoVo> friendRequestList(Integer userId, PageValidate pageValidate) {
		Integer pageNo = pageValidate.getPageNo();
		Integer pageSize = pageValidate.getPageSize();
		MPJQueryWrapper<UserFriendRequest> mpjQueryWrapper = new MPJQueryWrapper<>();
		/*mpjQueryWrapper.select("t.id,t.user_id,u.avatar as head_pic,u.nickname as name,f.phone,DATE_FORMAT(f.birthday,'%m月%d日') as birthday_show,f.address,f.position,"
				+ "f.unit_name,f.tax_number,f.unit_address,f.unit_phone,f.bank_name,f.bank_card,t.type");
		mpjQueryWrapper.leftJoin("?_user_friend f on t.user_id = f.user_id".replace("?_", GlobalConfig.tablePrefix));
		mpjQueryWrapper.leftJoin("?_user u on u.id = f.user_id".replace("?_", GlobalConfig.tablePrefix));*/
		mpjQueryWrapper.select("t.id,t.user_id,u.avatar as head_pic,u.nickname as name,u.mobile phone,DATE_FORMAT(u.birthday,'%m月%d日') as birthday_show,f.address,f.position,"
				+ "f.unit_name,f.tax_number,f.unit_address,f.unit_phone,f.bank_name,f.bank_card,t.type");
		mpjQueryWrapper.leftJoin("?_user_friend f on t.user_id = f.uid".replace("?_", GlobalConfig.tablePrefix));
		mpjQueryWrapper.leftJoin("?_user u on u.id = t.user_id".replace("?_", GlobalConfig.tablePrefix));
		mpjQueryWrapper.eq("t.to_user_id", userId);
		mpjQueryWrapper.eq("t.status", 1);
		mpjQueryWrapper.eq("t.type",0);
		mpjQueryWrapper.orderByDesc("t.create_time");
		IPage<FriendInfoVo> iPage = userFriendRequestMapper.selectJoinPage( new Page<>(pageNo, pageSize), FriendInfoVo.class, mpjQueryWrapper);
		iPage.getRecords().stream().forEach(vo ->{
			 if (StringUtils.isEmpty(vo.getHeadPic())) {
		            String avatar = ConfigUtils.get("user", "defaultAvatar", "");
		            vo.setHeadPic(UrlUtils.toAbsoluteUrl(avatar));
		        } else {
		            vo.setHeadPic(UrlUtils.toAbsoluteUrl(vo.getHeadPic()));
		        }
		});
		return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), iPage.getRecords());

//		LambdaQueryWrapper<UserFriendRequest> lambdaQueryWrapper = new LambdaQueryWrapper<UserFriendRequest>();
//		lambdaQueryWrapper.eq(UserFriendRequest::getType, 0);
//		lambdaQueryWrapper.eq(UserFriendRequest::getStatus, 1);
//		lambdaQueryWrapper.and(i ->i.eq(UserFriendRequest::getUserId, userId).or().eq(UserFriendRequest::getToUserId, userId));
//		List<UserFriendRequest> list = userFriendRequestMapper.selectList(lambdaQueryWrapper);
//		Page<UserFriend> iPage = new Page<UserFriend>();
//		List<Integer> userIds = new ArrayList<Integer>();
//		if(CollectionUtils.isNotEmpty(list)) {
//			for (UserFriendRequest userFriendRequest : list) {
//				if(userId.intValue() == userFriendRequest.getUserId().intValue()) {
//					userIds.add(userFriendRequest.getToUserId());
//				}else {
//					userIds.add(userFriendRequest.getUserId());
//				}
//			}
//			iPage = userFriendMapper.selectPage(new Page<UserFriend>().setCurrent(pageNo).setSize(pageSize), new LambdaQueryWrapper<UserFriend>().in(UserFriend::getUserId, userIds));
//			iPage.getRecords().stream().forEach(result ->{
//				if(null != result.getBirthday()) {
//					result.setBirthdayShow(DateUtils.format(result.getBirthday(), "MM月dd日"));
//				}
//			});
//		}
//		return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), iPage.getRecords());
	}


	@Override
	public AjaxResult<Object> addUserGroup(UserFriendGroup userFriendGroup, Integer userId) {
		Long count = userFriendGroupMapper.selectCount(new LambdaQueryWrapper<UserFriendGroup>().eq(UserFriendGroup::getGroupName, userFriendGroup.getGroupName())
				.eq(UserFriendGroup::getUserId, userId));
		if(count > 0) {
			return AjaxResult.failed("分组名已经存在");
		}
		userFriendGroup.setUserId(userId);
		userFriendGroup.setCreateTime((System.currentTimeMillis() / 1000));
		userFriendGroupMapper.insert(userFriendGroup);
		return AjaxResult.success();
	}
	@Override
	public AjaxResult<Object> updUserGroup(UserFriendGroup userFriendGroup, Integer userId) {
		Long count = userFriendGroupMapper.selectCount(new LambdaQueryWrapper<UserFriendGroup>().eq(UserFriendGroup::getGroupName, userFriendGroup.getGroupName())
				.ne(UserFriendGroup::getId, userFriendGroup.getId()));
		if(count > 0) {
			return AjaxResult.failed("分组名已经存在");
		}
		userFriendGroup.setUpdateTime((System.currentTimeMillis() / 1000));
		userFriendGroupMapper.updateById(userFriendGroup);
		return AjaxResult.success();
	}


	@Override
	public AjaxResult<Object> setUserGroup(UserFriendGroup userFriendGroup, Integer userId) {
		if(null != userFriendGroup.getId()) {
			UserFriendGroup group = userFriendGroupMapper.selectOne(new LambdaQueryWrapper<UserFriendGroup>().eq(UserFriendGroup::getId, userFriendGroup.getId()
					).eq(UserFriendGroup::getUserId, userId));
			Assert.notNull(group, "分组不存在");
			if(StringUtils.isEmpty(group.getToUserId())) {
				group.setToUserId(userFriendGroup.getToUserId());
			}else if(group.getToUserId().contains(userFriendGroup.getToUserId())) {
				return AjaxResult.failed("此用户已经在该分组");
			}else {
				group.setToUserId(group.getToUserId()+","+userFriendGroup.getToUserId());
			}
			// 处理用户是否在其他分组
			UserFriendGroup selectOne = userFriendGroupMapper.selectOne(new LambdaQueryWrapper<UserFriendGroup>().like(UserFriendGroup::getToUserId, userFriendGroup.getToUserId())
					.last("limit 1"));
			if(null != selectOne) {
				selectOne.setToUserId(handleToUserId(selectOne.getToUserId(), userFriendGroup.getToUserId()));
				selectOne.setUpdateTime((System.currentTimeMillis() / 1000));
				userFriendGroupMapper.updateById(selectOne);
			}
			group.setUpdateTime((System.currentTimeMillis() / 1000));
			userFriendGroupMapper.updateById(group);
		}else {
			UserFriendGroup group = userFriendGroupMapper.selectOne(new LambdaQueryWrapper<UserFriendGroup>().eq(UserFriendGroup::getType, 1
					).eq(UserFriendGroup::getUserId, userId));
			if(null == group) {
				group = new UserFriendGroup();
				group.setUserId(userId);
				group.setToUserId(userFriendGroup.getToUserId());
				group.setGroupName("特别关注");
				group.setType(1);
				group.setCreateTime((System.currentTimeMillis() / 1000));
				userFriendGroupMapper.insert(group);
			}else if(group.getToUserId().contains(userFriendGroup.getToUserId())) {
				return AjaxResult.failed("此用户已经在该分组");
			}else {
				group.setToUserId(group.getToUserId()+","+userFriendGroup.getToUserId());
				group.setUpdateTime((System.currentTimeMillis() / 1000));
				userFriendGroupMapper.updateById(group);
			}
		}
		return AjaxResult.success();
	}

	@Override
	public AjaxResult<Object> removeFollow(String toUserId, Integer userId) {
		UserFriendGroup group = userFriendGroupMapper.selectOne(new LambdaQueryWrapper<UserFriendGroup>().eq(UserFriendGroup::getType, 1
				).eq(UserFriendGroup::getUserId, userId));
		if(null == group || StringUtils.isEmpty(group.getToUserId()) || !group.getToUserId().contains(toUserId)) {
			return AjaxResult.failed("未在分组中");
		}
		String[] split = group.getToUserId().split(",");
		String newUserId = "";
		for (String string : split) {
			if(!string.equals(toUserId)) {
				newUserId += string+",";
			}
		}
		if(StringUtils.isNotEmpty(newUserId)) {
			newUserId = newUserId.substring(0,newUserId.length()-1);
		}
		group.setToUserId(newUserId);
		group.setUpdateTime(TimeUtils.timestamp());
		userFriendGroupMapper.updateById(group);
		return AjaxResult.success();
	}
	
	public static void main(String[] args) {
		String group = "218";
		String[] split = group.split(",");
		String newUserId = "";
		for (String string : split) {
			if(!string.equals("218")) {
				newUserId += string+",";
			}
		}
		if(StringUtils.isNotEmpty(newUserId)) {
			System.out.println(newUserId.substring(0,newUserId.length()-1));
		}else {
			System.out.println(newUserId);
		}
		
		
		
	}

	/**
	 * 	处理用户ID
	 * @param toUserIdList
	 * @param toUserId
	 * @return
	 */
	private String handleToUserId(String toUserIdList,String toUserId) {
		String retStr = "";
		String[] split = toUserIdList.split(",");
		for (int i = 0; i < split.length; i++) {
			if(!split[i].equals(toUserId)) {
				retStr +=split[i]+",";
			}
		}
		return retStr.substring(0, retStr.length()-1);
	}

	@Override
	public PageResult<UserFriend> specialFriendList(Integer userId, PageValidate pageValidate) {
		Integer pageNo = pageValidate.getPageNo();
		Integer pageSize = pageValidate.getPageSize();

		UserFriendGroup group = userFriendGroupMapper.selectOne(new LambdaQueryWrapper<UserFriendGroup>().eq(UserFriendGroup::getUserId, userId).eq(UserFriendGroup::getType, 1)
				.last("limit 1"));
		if(null == group || StringUtils.isEmpty(group.getToUserId())) {
			return PageResult.iPageHandle(0L, 0L, 0L, null);
		}
		List<String> asList = Arrays.asList(group.getToUserId().split(","));
		Page<UserFriend> iPage = userFriendMapper.selectPage(new Page<>(pageNo, pageSize), new LambdaQueryWrapper<UserFriend>().in(UserFriend::getUserId, asList));
		iPage.getRecords().stream().forEach(user ->{
			if(null != user.getBirthday()) {
				user.setBirthdayShow(DateUtils.format(user.getBirthday(), "MM月dd日"));
			}
		});
		return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), iPage.getRecords());
	}


	@Override
	public List<UserLableGroupVo> lableGroupList(Integer userId) {
		MPJQueryWrapper<UserFriendRequest> mpjQueryWrapper = new MPJQueryWrapper<>();
		mpjQueryWrapper.select("f.id,t.user_id,f.head_pic,f.name,f.phone,DATE_FORMAT(f.birthday,'%m月%d日') as birthdayShow,f.address,f.position,"
				+ "f.unit_name,f.tax_number,f.unit_address,f.unit_phone,f.bank_name,f.bank_card");
		mpjQueryWrapper.leftJoin("?_user_friend f on (t.user_id = f.user_id or t.to_user_id = f.user_id)".replace("?_", GlobalConfig.tablePrefix));
		mpjQueryWrapper.eq("t.type", 1);
		mpjQueryWrapper.eq("t.status", 1);
		mpjQueryWrapper.and(i ->i.eq("t.to_user_id", userId).or().eq("t.user_id", userId));
		mpjQueryWrapper.orderByDesc("t.create_time");
		mpjQueryWrapper.groupBy("t.user_id");
		List<UserFriend> wholeList = userFriendRequestMapper.selectJoinList(UserFriend.class, mpjQueryWrapper);
		List<UserLableGroupVo> list1 = new ArrayList<UserLableGroupVo>();
		UserLableGroupVo vo = new UserLableGroupVo();
		vo.setGroupName("全部");
		if(CollectionUtils.isEmpty(wholeList)) {
			vo.setList(new ArrayList<UserFriend>());
		}else {
			vo.setList(wholeList);
		}
		list1.add(vo);
		List<UserFriendGroup> groupList = userFriendGroupMapper.selectList(new LambdaQueryWrapper<UserFriendGroup>().eq(UserFriendGroup::getUserId, userId).eq(UserFriendGroup::getType, 0));
		groupList.stream().forEach(group ->{
			UserLableGroupVo vo1 = new UserLableGroupVo();
			vo1.setGroupName(group.getGroupName());
			vo1.setGroupId(group.getId());
			if(StringUtils.isNotEmpty(group.getToUserId())) {
				List<String> asList = Arrays.asList(group.getToUserId().split(","));
				List<UserFriend> list = userFriendMapper.selectList(new LambdaQueryWrapper<UserFriend>().in(UserFriend::getUserId, asList));
				if(CollectionUtils.isNotEmpty(list)) {
					vo1.setList(list);
				}
			}
			list1.add(vo1);
		});
		return list1;
	}


	@Override
	public PageResult<FriendInfoVo> userBlacklist(Integer userId, PageValidate pageValidate) {
		Integer pageNo = pageValidate.getPageNo();
		Integer pageSize = pageValidate.getPageSize();
		MPJQueryWrapper<UserBlacklist> mpjQueryWrapper = new MPJQueryWrapper<>();
		mpjQueryWrapper.select("f.id,t.to_user_id as user_id,f.head_pic,f.name,f.phone,DATE_FORMAT(f.birthday,'%m月%d日') as birthdayShow,f.address,f.position,"
				+ "f.unit_name,f.tax_number,f.unit_address,f.unit_phone,f.bank_name,f.bank_card");
		mpjQueryWrapper.leftJoin("?_user_friend f on t.to_user_id = f.user_id ".replace("?_", GlobalConfig.tablePrefix));
		mpjQueryWrapper.eq("t.user_id", userId);
		mpjQueryWrapper.orderByDesc("t.create_time");
		IPage<FriendInfoVo> iPage = userBlacklistMapper.selectJoinPage(new Page<>(pageNo, pageSize), FriendInfoVo.class, mpjQueryWrapper);
		return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), iPage.getRecords());
	}


	@Override
	public AjaxResult<Object> blockOrUnBlock(Integer userId, Integer toUserId) {
		UserBlacklist black = userBlacklistMapper.selectOne(new LambdaQueryWrapper<UserBlacklist>().eq(UserBlacklist::getUserId, userId).eq(UserBlacklist::getToUserId, toUserId));
		if(null == black) {
			black = new UserBlacklist();
			black.setUserId(userId);
			black.setToUserId(toUserId);
			black.setCreateTime((System.currentTimeMillis() / 1000));
			userBlacklistMapper.insert(black);
		}else {
			if (black != null) {
				userBlacklistMapper.deleteById(black.getId());
			}
		}
		return AjaxResult.success();
	}


	@Override
	public AjaxResult<Object> applyforFriend(Integer userId, Integer toUserId) {
		UserFriendRequest request = userFriendRequestMapper.selectOne(new LambdaQueryWrapper<UserFriendRequest>().eq(UserFriendRequest::getUserId, userId)
				.eq(UserFriendRequest::getToUserId, toUserId));
		if(null == request) {
			request = new UserFriendRequest();
			request.setUserId(userId);
			request.setToUserId(toUserId);
			request.setType(0);
			request.setCreateTime((System.currentTimeMillis() / 1000));
			userFriendRequestMapper.insert(request);
		}else {
			switch (request.getType()) {
			case 0:
				return AjaxResult.failed("已申请,等待对方同意");
			case 1:
				return AjaxResult.failed("已经是好友了");
			case 2:
				request.setType(0);
				userFriendRequestMapper.updateById(request);
				break;
			default:
				break;
			}
		}
		return AjaxResult.success();
	}

	@Override
	public AjaxResult<Object> applyforFriendHandle(Integer userId, UserFriendRequest userFriendRequest) {
		UserFriendRequest request = userFriendRequestMapper.selectOne(new LambdaQueryWrapper<UserFriendRequest>().eq(UserFriendRequest::getToUserId, userId)
				.eq(UserFriendRequest::getId, userFriendRequest.getId()));
		Assert.notNull(request, "好友请求不存在");
		if(0 == request.getType()) {
			request.setType(userFriendRequest.getType());
			request.setUpdateTime((System.currentTimeMillis() / 1000));
			userFriendRequestMapper.updateById(request);
			return AjaxResult.success();
		}else {
			return AjaxResult.failed("已处理");
		}
	}


	@Override
	public AjaxResult<Object> delFriend(Integer userId, Integer toUserId) {
		LambdaQueryWrapper<UserFriendRequest> lambdaQueryWrapper = new LambdaQueryWrapper<UserFriendRequest>();
		lambdaQueryWrapper.and(i ->i.eq(UserFriendRequest::getUserId, userId).or().eq(UserFriendRequest::getUserId, toUserId));
		lambdaQueryWrapper.and(i ->i.eq(UserFriendRequest::getToUserId, userId).or().eq(UserFriendRequest::getToUserId, toUserId));
		UserFriendRequest request = userFriendRequestMapper.selectOne(lambdaQueryWrapper);
		if(null != request) {
			request.setStatus(0);
			userFriendRequestMapper.updateById(request);
		}
		return AjaxResult.success();
	}


	@Override
	public UserFriend friendDetail(Integer userId, Integer toUserId) {
		UserFriend userFriend = userFriendMapper.selectOne(new LambdaQueryWrapper<UserFriend>()
				.eq(UserFriend::getUserId, toUserId).eq(UserFriend::getUid, userId));
		if(null == userFriend) {
			userFriend = userFriendMapper.selectOne(new LambdaQueryWrapper<UserFriend>()
					.eq(UserFriend::getUserId, toUserId).last("limit 1"));
		}
		Assert.notNull(userFriend, "好友不存在");
		// 查询nickname
		User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, userFriend.getUserId()).select(User::getId,User::getNickname));
		if(null != user && StringUtils.isNotEmpty(user.getNickname())) {
			userFriend.setNickName(user.getNickname());
		}
		// 处理生日
		if(null != userFriend.getBirthday()) {
			userFriend.setBirthdayShow(DateUtils.format(userFriend.getBirthday(), "yyyy年MM月dd日"));
			// 处理星座
			userFriend.setConstellation(TimeUtils.constellation(userFriend.getBirthday()));
			// 处理生肖
			userFriend.setZodica(TimeUtils.getZodica(userFriend.getBirthday()));
			// 生日描述
			try {
				userFriend.setBirthdayRemark("【距"+TimeUtils.getAge(userFriend.getBirthday())+"岁："+TimeUtils.calcBirthDay(userFriend.getBirthday())+"天】");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// 处理好友状态
		Long count = userBlacklistMapper.selectCount(new LambdaQueryWrapper<UserBlacklist>().eq(UserBlacklist::getUserId, userId).eq(UserBlacklist::getToUserId, toUserId));
		if(count > 0) {
			userFriend.setFriendStatus(2);
		}
		Long selectCount = userFriendGroupMapper.selectCount(new LambdaQueryWrapper<UserFriendGroup>().eq(UserFriendGroup::getUserId, userId).eq(UserFriendGroup::getToUserId, toUserId)
				.eq(UserFriendGroup::getType, 1));
		if(selectCount > 0) { // 特别关心
			userFriend.setFriendStatus(3);
		}else {	// 获取分组ID和名称
			UserFriendGroup group = userFriendGroupMapper.selectOne(new LambdaQueryWrapper<UserFriendGroup>().eq(UserFriendGroup::getUserId, userId).eq(UserFriendGroup::getToUserId, toUserId)
					.eq(UserFriendGroup::getType, 0).last("limit 1"));
			if(null != group) {
				userFriend.setGroupId(group.getId());
				userFriend.setGroupName(group.getGroupName());
			}
		}
		return userFriend;
	}


	@Override
	public AjaxResult<Object> setCommemorate(Integer userId, UserCommemorate userCommemorate) {
		userCommemorate.setUserId(userId);
		userCommemorate.setCreateTime(TimeUtils.timestamp());
		userCommemorateMapper.insert(userCommemorate);
		return AjaxResult.success();
	}


	@Override
	public PageResult<UserCommemorateVo> userCommemorateList(Integer currUserId, Integer userId,PageValidate pageValidate) {
		Integer pageNo = pageValidate.getPageNo();
		Integer pageSize = pageValidate.getPageSize();
		MPJQueryWrapper<UserCommemorate> mpjQueryWrapper = new MPJQueryWrapper<>();
		mpjQueryWrapper.select("t.id,t.uid,t.user_id,t.name,t.is_remind,DATE_FORMAT(t.time,'%Y年%m月%d日') as timeShow,t.time ");
		mpjQueryWrapper.eq("t.uid", userId);
		mpjQueryWrapper.eq("t.user_id", currUserId);
		mpjQueryWrapper.orderByDesc("t.create_time");
		IPage<UserCommemorateVo> iPage = userCommemorateMapper.selectJoinPage( new Page<>(pageNo, pageSize), UserCommemorateVo.class, mpjQueryWrapper);
		iPage.getRecords().stream().forEach(comm ->{
			comm.setName("距【"+comm.getName()+"】"+TimeUtils.calcBirthDay(comm.getTime())+"天");
		});
		return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), iPage.getRecords());
	}


	@Override
	public AjaxResult<Object> commemorateRemind(Integer userId, Integer id) {
		UserCommemorate userCommemorate = userCommemorateMapper.selectById(id);
		Assert.notNull(userCommemorate, "纪念日不存在");
		User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, userCommemorate.getUid()).select(User::getId,User::getNickname));
		Assert.notNull(user, "用户不存在");
		// 添加到定时任务表 
		UserTask task = new UserTask();
		task.setUserId(userId);
		task.setType(1);
		task.setStatus(0);
		task.setTitle("纪念日提醒");
		task.setContent("您与好友“"+user.getNickname()+"”的纪念日【"+userCommemorate.getName()+"】仅剩10天！");
		task.setCreateTime(TimeUtils.timestamp());
		userTaskMapper.insert(task);
		return AjaxResult.success();
	}


	@Override
	public AjaxResult<Object> deleteCommunicate(Integer userId, Integer id) {
		userFriendMapper.deleteById(id);
		return AjaxResult.success();
	}

}
